<?php

class BasePlugin extends Yaf_Plugin_Abstract {
    public function routerStartup(Yaf_Request_Abstract $request, Yaf_Response_Abstract $response) {
        $client_ip = $this->get_ip();
        $ips = [
            '127.0.0.1',
            '106.14.240.239',
            '106.15.3.22',
            '47.101.70.247',
            '47.103.156.180',
            '47.100.160.43',
            '106.15.249.106',
            '111.196.180.18',
            '221.219.96.36',
            '120.245.115.140'
        ];
        $allow_ips = array();
        foreach($ips as $val){
            if(substr(strrchr($val, "."),1) == "*"){
                $val = substr($val,0,-2);
            }
            $allow_ips[] = $val;
        }
        if($ips){
            if(!in_array($client_ip,$allow_ips) && !in_array(substr($client_ip,0,strrpos($client_ip, ".")),$allow_ips)) {
                $returnData = array(
                    'code'=>4003,
                    'message'=>'非法请求',
                    'data'=>[]
                );
                Func_Log::write('thirdrequest', 'error', 'client_ip =' . $client_ip);

                header("Content-type: application/json");
                echo json_encode($returnData);
                exit;
            }
        }
	}

	public function routerShutdown(Yaf_Request_Abstract $request, Yaf_Response_Abstract $response) {

    }


    private function get_ip(){

        $realip = '0.0.0.0';

        if (isset($_SERVER)){
            if (isset($_SERVER['HTTP_X_FORWARDED_FOR'])){
                $arr = explode(',', $_SERVER['HTTP_X_FORWARDED_FOR']);
                /* 取X-Forwarded-For中第一个非unknown的有效IP字符串 */
                foreach ($arr AS $ip){
                    $ip = trim($ip);

                    if ($ip != 'unknown'){
                        $realip = $ip;

                        break;
                    }
                }
            }
            elseif (isset($_SERVER['HTTP_CLIENT_IP'])){
                $realip = $_SERVER['HTTP_CLIENT_IP'];
            }
            else{
                if (isset($_SERVER['REMOTE_ADDR'])){
                    $realip = $_SERVER['REMOTE_ADDR'];
                }
                else{
                    $realip = '0.0.0.0';
                }
            }
        }
        else{
            if (getenv('HTTP_X_FORWARDED_FOR')){
                $realip = getenv('HTTP_X_FORWARDED_FOR');
            }
            elseif (getenv('HTTP_CLIENT_IP')){
                $realip = getenv('HTTP_CLIENT_IP');
            }
            else{
                $realip = getenv('REMOTE_ADDR');
            }
        }

        preg_match("/[\d\.]{7,15}/", $realip, $onlineip);
        $realip = !empty($onlineip[0]) ? $onlineip[0] : '0.0.0.0';

        return $realip;
    }

}
